import java.text.DateFormat


class PersonController {
  static allowedMethods = [delete:'POST', save:'POST', update:'POST']
  def index = { redirect(action:list,params:params) }
    
  def list = {
    params.max = Math.min( params.max ? params.max.toInteger() : 10,  100)
    [personInstanceList: Person.list( params ), personInstanceTotal: Person.count()]
  }

  def show = {
    def personInstance = Person.get(params.id)
    if(!personInstance) {
      flash.message = "Person not found with id ${params.id}"
      redirect(action:list)
    }
    else
      return [personInstance:personInstance]
  }

  def delete = {
    def personInstance = Person.get(params.id)
    if(personInstance) {
      try {
	personInstance.delete(flush:true)
	flash.message = "Person ${params.id} deleted"
	redirect(action:list)
      }
      catch(org.springframework.dao.DataIntegrityViolationException e) {
	flash.message = "Person ${params.id} could not be deleted"
	redirect(action:show, id:params.id)
      }
    }
    else {
      flash.message = "Person not found with id ${params.id}"
      redirect(action:list)
    }
  }

  def edit = {
    def personInstance = Person.get(params.id)
    if(!personInstance) {
      flash.message = "Person not found with id ${params.id}"
      redirect(action:list)
    }
    else {
      return [ personInstance : personInstance ]
    }
  }

  def update = {
    def personInstance = Person.get(params.id)
    if(personInstance) {
      if(params.version) {
	def version = params.version.toLong()
	if(personInstance.version > version) {
	  personInstance
	  .errors
	  .rejectValue("version", "person.optimistic.locking.failure", 
		       "Another user has updated this Person while you were editing.")
	  render(view:'edit',model:[personInstance:personInstance])
	  return
	}
      }
      personInstance.properties = params
      if(!personInstance.hasErrors() && personInstance.save()) {
	def cvFile = request.getFile('cv')
	if (!cvFile.isEmpty())
	  personInstance.saveCV(cvFile)
	flash.message = "Person ${params.id} updated"
	redirect(action:show,id:personInstance.id)
      }
      else {
	render(view:'edit',model:[personInstance:personInstance])
      }
    }
    else {
      flash.message = "Person not found with id ${params.id}"
      redirect(action:list)
    }
  }

  def create = {
    return ['personInstance':new Person(params)]
  }

  def save = {
    params.birthday = Date.parseOrNull(params.birthday)
    def personInstance = new Person(params)
    if(!personInstance.hasErrors() && personInstance.save()) {
      def cvFile = request.getFile('cv')
      if (!cvFile.isEmpty())
	personInstance.saveCV(cvFile)
      flash.message = "Person ${personInstance.id} created"
      redirect(action:show, id:personInstance.id)
    }
    else {
      render(view:'create', model:[personInstance:personInstance])
    }
  }

  def downloadCV = {
    def personInstance = Person.get(params.id)
    response.setContentType("application/octet-stream")
    response.setHeader("Content-disposition",
		       "attachment;filename=${personInstance.getCVFileName()}")
    response.outputStream << personInstance.getCVFile().newInputStream()
    redirect(action:show, id:personInstance.id)
  }

  def vacationList = {
    def person = Person.get(params.id.toLong())
    def vacationsDates = person.getVacationsDates({ "'" + g.format(date:it) + "'" })
    params.max = Math.min( params.max ? params.max.toInteger() : 10,  100)
    return [vacationInstanceList: person.vacations, 
	    vacationInstanceTotal: person.vacations.count(), 
	    person:person,
	    vacationsDates:"[" + vacationsDates.join(', ') + "]"]
  }

  def createVacation = {
    return ['vacationInstance':new Vacation(params), person:Person.get(params.id.toLong())]
  }

  def saveVacation = {
    def personInstance = Person.get(params.personId.toLong())

    params.startDate = Date.parseOrNull(params.startDate)
    params.endDate = Date.parseOrNull(params.endDate)

    def vacationInstance = new Vacation(params)
    if(!vacationInstance.hasErrors() && vacationInstance.save()) {
      personInstance.addToVacations(vacationInstance).save()
      flash.message = "Vacation ${vacationInstance.id} for ${personInstance.lastName} created"
      redirect(action:show, id: personInstance.id, personInstance: personInstance)
    }
    else {
      render(view:'createVacation', model:['vacationInstance': vacationInstance, 
					   'person': personInstance, 
					   'id': params.personId])
    }
  }

  def teamList = {
    def person = Person.get(params.id.toLong())
    def teamInstanceList = Team.executeQuery(
      "select t from Team as t inner join t.members as p where p.id=:id",
      [id:person.id])
    println teamInstanceList
    params.max = Math.min(params.max ? params.max.toInteger() : 10,  100)
    return [teamInstanceList  : teamInstanceList,
	    teamInstanceTotal : teamInstanceList.count(),
	    person : person]
  }
}
